﻿/*
* 作者:haojielyb
* 邮箱:haojielyb@qq.com
*/

using Furion.DependencyInjection;
using Furion.Logging.Extensions;
using FaceMqttClient.model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace FaceMqttClient

{
    public class UserService : ITransient
    {
        private readonly ISugarQueryable<Users> repository; // 仓储对象：封装简单的CRUD
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private string path = AppDomain.CurrentDomain.BaseDirectory;

        public UserService(ISqlSugarClient db)
        {
            repository = db.Queryable<Users>();
            this.db = db;     // 推荐操作
        }
  



        public List<VUsers> Getall(String devid, int size = 50, int page = 0)
        {
            var dev_ = db.Queryable<Device>().Where(dev => dev.SN == devid && dev.down!=0).First();

            if (dev_ == null)
            {
                return null;
            }
          

            var school = dev_.school;

            var aschool = db.Queryable<School>().Where(sc => sc.name == school).First();

            if (aschool == null)
            {
                aschool = new School { zhusu = "", zoudu = "" };
            }
            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);

            var afd = db.Queryable<Face_down_log>().Where(fd => fd.SN == devid).Max(fd => fd.time);

            if (afd > datetime)
            {
                datetime = afd;
            }

            var devdata = db.Queryable<Device_data>().Where(dd => dd.lxb_device == dev_.Id).ToList();

            var sql = $"  INSERT INTO lxb_face_down_log(uid,time,status,SN) " +
                $" select user_id as uid, uptime as time,  0 as status, '{devid}' as SN from lxb_user" +
                $" where  feature<>'' and  slname='{school}' and  uptime > '{datetime.ToString("yyyy/MM/dd HH:mm:ss")}'";

            foreach (var wdev in devdata)
            {
                if (wdev.state > 0)
                {
                    sql = sql + $" and  state =   {wdev.state}";
                }

                if (!String.IsNullOrEmpty(wdev.classname))
                {
                    sql = sql + $" and  clname = '{wdev.classname}'";
                }
            }

            db.Ado.ExecuteCommand(sql);

            var avu = db.Queryable<Face_down_log, Users>((fd, u) =>
       new JoinQueryInfos(
           JoinType.Inner, fd.uid == u.user_id)
       ).Where((fd, u) => fd.status == 0 && fd.times < 5 && u.feature != "" && fd.SN == devid)
       .Select((fd, u) => new VUsers
       {
           Id = fd.Id,
           face = u.feature,
           clname = u.clname,
           slname = u.slname,
           username = u.username,
           user_id = u.user_id,
           zschool = u.zschool,
           dx=u.dx,
           state = u.state,
           uptime = fd.time
       })
       .OrderBy(fd => fd.Id, OrderByType.Asc).Take(size).ToList();

            foreach (var item in avu)
            {
                if (item.state > 2)
                {
                    if (item.zschool.Trim() == "是")
                    {
                        item.username = aschool.zhusu + item.username;
                    }
                    else
                    {

                        if (item.dx.Trim() == "是")
                        {
                            item.username = "午餐" + item.username;
                        }
                        else
                        {
                            item.username = aschool.zoudu + item.username;
                        }


                      
                    }
                }
            }
            //try
            //{
            //    item.face = db.Queryable<Face>().Where(f => f.uid == item.user_id).First().face;
            //}
            //catch
            //{
            //    item.face = null;
            //}
            //.Skip(page * size).Take(size)

            return avu;
        }

        private String dellasttime = "";

        public List<Users_del> GetDel(String devid, int size = 50, int page = 0)
        {
            var dev_ = db.Queryable<Device>().Where(dev => dev.SN == devid).First();

            if (dev_ == null)
            {
                return null;
            }

            var school = dev_.school;

            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);
            try
            {
                datestr = System.IO.File.ReadAllText($"{path}dev/{devid}_d.cfg");
                datetime = Convert.ToDateTime(datestr);
            }
            catch (Exception)
            {
                datestr = "2018/1/1";
            }

            var lst = db.Queryable<Users_del>().Where(d => d.deltime > datetime && d.School == school).OrderBy(d => d.deltime, OrderByType.Asc).Skip(page * size).Take(size).ToList();
            if (lst.Count > 0)
            {
                dellasttime = lst.Last().deltime.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (lst.Count < size && (!String.IsNullOrEmpty(dellasttime)))
            {
                try
                {
                    if (!Directory.Exists($"{path}dev/"))
                    {
                        Directory.CreateDirectory($"{path}dev/");
                    }
                    System.IO.File.WriteAllText($"{path}dev/{devid}_d.cfg", dellasttime);

                }
                catch (Exception ex)
                {

                    ex.Message.SetCategory("UserService").LogInformation();
                }
               
            }
            return lst;
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="base64Img"></param>
        /// <param name="imgPath"></param>
        /// <param name="imgFormat">EX: System.Drawing.Imaging.Jpeg </param>
        public void SaveFile(VUsers u)
        {
            var imgPath = @$"E:\weixin\face_build\{u.user_id}.jpg";
            File.Exists(imgPath);
            var dateTime = File.GetLastWriteTime(imgPath);
            if (dateTime > u.uptime)
            {
                return;
            }
            string dir = Path.GetDirectoryName(imgPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            OthTool.Base64StringToImage(u.face, imgPath);
           
              
           
        }
    }
}